<template>
  <div class="menu_box">
    <div class="menu_left" @click="goHome">
      <n-icon :component="Home" size="22"/>
      <div style="font-weight: 700;font-size: 20px;padding-left: 10px;text-align: center;">主页</div>
    </div>
    <div class="menu_center" v-if="isSearch">
      <n-input placeholder="可搜索当前空间的文章" v-model:value="searchInputValue" @update:value="searchSpace">
        <template #suffix>
          <n-icon :component="SearchSharp" />
        </template>
      </n-input>
    </div>
    <div class="menu_right">
      <div class="menu_right_left" @click="router.push('/showSpace')">
        <n-button quaternary size="small">
          寻找空间
        </n-button>
      </div>
      <div class="menu_right_left" @click="router.push('/createSpace')">
        <n-button quaternary size="small">
          创建空间
        </n-button>
      </div>
      <div class="menu_right_left" @click="switchTheme">
        <n-button quaternary size="small">
          {{ theme_text }}
        </n-button>
      </div>
      <div class="menu_right_center">
        <n-dropdown trigger="hover" :options="options" @select="handleSelect" style="padding: 10px;">
          <n-avatar
            v-if="user_avatar"
            round
            size="small"
            :src="host + '/api/' + user_avatar"
            class="menu_avatar"
            @click="goPerson"
          />
          <n-avatar
            v-else
            class="menu_avatar"
            size="small"
            round
            :style="{
              color: 'yellow',
            }"
            @click="goPerson"
          >
            {{ username.slice(0,1) }}
          </n-avatar>
        </n-dropdown>
      </div>
      <div class="menu_right_right" title="消息" @click="router.push(`/message/myMessage/${message_user_id}`)">
        <n-icon :component="NotificationsOutline" size="22"/>
        <div class="msg-tip" v-if="msg_count">{{ msg_count }}</div>
      </div>
    </div>
  </div>

  <updateUserMessage :updateUserModal="updateUserModal" @closeModal="updateUserModal = false"></updateUserMessage>
</template>

<script setup lang='ts'>
import {essayListType} from "../types"
import { SearchSharp, NotificationsOutline,Home } from '@vicons/ionicons5'
import {ref,onMounted,inject, watch} from "vue"
import updateUserMessage from "./updateUserMessage.vue"
import {getUnreadMsg} from "../api/message"
import {useStore} from "../store/index"
import { useRouter, useRoute } from "vue-router"
const router = useRouter()
const route = useRoute()
const store = useStore()

const host = ref(inject("host"))

const updateUserModal = ref(false)
const username = ref("")
const user_avatar = ref("")
const msg_count = ref(0)
const theme_text = ref(store.osTheme=="dark"?"浅色":"深色")
const message_user_id = ref(0)
const searchInputValue = ref("")

const user_id = localStorage.getItem("user_id")
var socket = new WebSocket(`ws://${window.location.host}/ws/room/${user_id}`)
// 监听消息
socket.onmessage = (e) => {
  const res_data = JSON.parse(e.data)
  if(res_data.from_user_id != user_id){
    message_user_id.value = res_data.from_user_id
    // 更新未读消息数量
    msg_count.value++
  }
}

defineProps<{
  isSearch: boolean
}>()

const options = [
  {
    label: '创建空间',
    key: 'createSpace',
  },
  {
    label: '我的文章',
    key: 'myEssay'
  },
  {
    label: '我的收藏',
    key: 'myCollect'
  },
  {
    label: '个人信息',
    key: 'userMess'
  },
  {
    label: '退出登录',
    key: 'exitLogin'
  }
]

const switchTheme = () => {
  if(store.osTheme == "dark"){
    store.setOsTheme("light")
    theme_text.value = "深色"
  }else{
    store.setOsTheme("dark")
    theme_text.value = "浅色"
  }
}

const goPerson = () => {
  const personUrl = router.resolve({
    path: "/person/" + localStorage.getItem("user_id")
  })
  window.open(personUrl.href, '_blank')
  // router.push("/person/" + localStorage.getItem("user_id"))
}

const handleSelect =(key:string) => {
  if(key == "createSpace"){
    router.push("/createSpace")
    return
  }
  if(key == "userMess"){
    updateUserModal.value = true
    return
  }
  if(key == "exitLogin"){
    localStorage.removeItem("token")
    // localStorage.removeItem("osTheme")
    localStorage.removeItem("username")
    localStorage.removeItem("user_id")
    localStorage.removeItem("avatar")
    router.push("/login")
    return
  }
}

const goHome = () => {
  if(route.name == "spaceHome") return
  router.push("/home")  
}

// 搜索
const searchSpace = (value:string) => {
  const searchEssayResult = store.essay_list.filter((e:essayListType) => e.essay_content.toUpperCase().includes(value.toUpperCase()))
  store.setSearchEssayResult(searchEssayResult)
}

onMounted(async() => {
  user_avatar.value = localStorage.getItem("avatar") || ""
  username.value = localStorage.getItem("username") || ""
  const user_id = Number(localStorage.getItem("user_id"))
  const unread_data = await getUnreadMsg(user_id)
  if(unread_data.code == "200") {
    msg_count.value = unread_data.data.unread_my_msg
    message_user_id.value = unread_data.data.default_user_id
    store.setUnReadMsg(unread_data.data.unread_my_msg)
  }else{
    window.$message.error(unread_data.message)
  }
})

watch(() => store.unReadMsg, async(newValue) => {
  msg_count.value= newValue
})
</script>

<style lang='scss' scoped>
  .menu_box{
    background-color: var(--bs-content-background);
    position: fixed;
    height: 50px;
    width: 100%;
    // background-color: rgb(250, 250, 252);
    box-shadow: 0 2px 12px 0 rgba(92, 199, 199, 0.7);
    z-index: 999;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .menu_left{
      // width: 200px;
      display: flex;
      align-items: center;
      margin-left: 30px;
      cursor: pointer;
    }
    .menu_left:hover{
      color: #63e2b7;
    }
    .menu_center{
      width: 600px;
      margin-left: 130px;
    }
    .menu_right{
      min-width: 200px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-right: 20px;
      .menu_right_left{
        cursor: pointer;
        margin: 0 5px;
      }
      .menu_right_center{
        cursor: pointer;
        margin: 0 20px;
        display: flex;
        align-items: center;

        .menu_avatar:hover{
          box-shadow: 0 2px 12px 0 rgba(92, 199, 199, 0.7);
        }
      }
      .menu_right_right{
        cursor: pointer;
        display: flex;
        .msg-tip{
          position: absolute;
          right: 8px;
          top: 10px;
          line-height: 16px;
          font-size: 12px;
          border-radius: 8px;
          height: 16px;
          min-width: 16px;
          // top: 15px;
          // right: 8px;
          padding: 0 4px;
          text-align: center;
          // position: absolute;
          background-color: #fb7299;
          box-sizing: border-box;
        }
      }
    }
  }
</style>